﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Web;
using AutoPartsSearch.Domain.Abstract;

namespace AutoPartsSearch.Web.Infrastructure
{
    public class SessionLanguageGetter : ILanguageGetter
    {
        private readonly string sessionKey = "__session_lang";
        private readonly string defaultCulture = "en-US";
        private readonly string[] allowedLanguages = new string[]{"ru-RU","ro-RO", "en-US"}; 

        public CultureInfo GetCurrentLanguage()
        {
            //if (HttpContext.Current.Session != null)
            //{
            //    CultureInfo ci = (CultureInfo)HttpContext.Current.Session[sessionKey];
                
            //    //Checking first if there is no value in session 
            //    //and set default language 
            //    //this can happen for first user's request
            //    if (ci == null)
            //    {
            //        //Sets default culture to english invariant
            //        string langName = "ru-RU";

            //        //Try to get values from Accept lang HTTP header
            //        if (HttpContext.Current.Request.UserLanguages != null && HttpContext.Current.Request.UserLanguages.Length != 0)
            //        {
            //            //Gets accepted list 
            //            langName = HttpContext.Current.Request.UserLanguages[0].Substring(0, 2);
            //        }
            //        langName = GetLanguage(langName);
            //        ci = new CultureInfo(langName);
            //        SetLanguage(ci);
            //    }
            //    ci.DateTimeFormat.ShortDatePattern = "dd.MM.yyyy";
            //    ci.DateTimeFormat.ShortTimePattern = "";
            //    return ci;
            //}
            return new CultureInfo(defaultCulture);
        }

        public void SetLanguage(System.Globalization.CultureInfo cultureInfo)
        {
            HttpContext.Current.Session[sessionKey] = cultureInfo;
        }

        private string GetLanguage(string langName)
        {
            if (string.IsNullOrEmpty(langName))
                return defaultCulture;
            var lang = allowedLanguages.FirstOrDefault(x => x.Contains(langName));
            return string.IsNullOrEmpty(lang) ? defaultCulture : lang;
        }
    }
}